// const { program } = require('commander');
const inquirer = require('inquirer');
const fs = require('fs-extra');
const path = require('path');
const pkg = require('../../package.json');
const ejs = require('ejs');
const { textSync } = require('figlet');
// const { commandSpawn } = require('../../utils/terminal');
const { blue, green } = require('chalk');
const ora = require('ora');

/**
 * 模板文件处理函数
 * @param {*} filePath 文件路径
 * @param {*} options targetPath finalProjectName projectDescription supportTs spinner
 * @param {*} file 如果是文件
 */
function processFile(filePath, options, file) {
  const fileStat = fs.statSync(filePath);
  const relativePath = path.relative(options.templatePath, filePath);
  const targetFilePath = path.resolve(
    options.targetPath + `${relativePath ? `/${relativePath}` : ''}`,
  );
  if (fileStat.isDirectory()) {
    // options?.spinner?.info?.(`downloadding: ${filePath}`);
    // console.log(`Processing directory: ${filePath}`);
    // 第一次进入没有 file
    file && fs.ensureDirSync(targetFilePath);
    // 如果 filePath 是一个目录，则递归调用 handleFiles 处理该目录
    handleFiles(filePath, { ...options, targetFilePath }, file);
  } else {
    // 判断是否为模板数据
    if (file.indexOf('.ejs') === -1) {
      // 直接拷贝 将文件直接拷贝
      fs.copySync(filePath, targetFilePath, { overwrite: true });
      return;
    }
    // 处理文件的逻辑
    const templateContent = fs.readFileSync(filePath, 'utf8');
    const renderedContent = ejs.render(templateContent, {
      projectName: options?.finalProjectName,
      projectDescription: options?.projectDescription,
      supportTs: options?.supportTs,
    });
    // 去掉 .ejs 后缀 相对位置为 package.json.ejs这种
    const targetFileName = relativePath.endsWith('.ejs') ? relativePath.slice(0, -4) : relativePath;
    const ejsFilePath = path.resolve(options.targetPath + `/${targetFileName}`);
    fs.writeFileSync(ejsFilePath, renderedContent);
  }
}

function handleFiles(directory, options) {
  const files = fs.readdirSync(directory);
  files.forEach((file) => {
    const filePath = path.join(directory, file);
    processFile(filePath, options, file);
  });
}

// const createVueCommand = require("./actions/vue");
const creteTemplateCommands = async (projectName, options) => {
  const template = options?.template || 'vue';
  let pn = projectName;
  if (pn) {
    // 首先我们先要判断当前目录下有没有用户输入项目名相同的文件夹,如果有再让用户选择是否覆盖,选择是就把文件夹覆盖,否的话就退出创建
    const targetPath = path.join(process.cwd(), pn); // 获取当前目录
    if (fs.existsSync(targetPath)) {
      const answer = await inquirer.prompt([
        {
          name: 'isOverwrite',
          type: 'confirm',
          message: '当前项目已存在,要覆盖不?',
          default: false,
        },
      ]);
      // 如果用户选择不覆盖,就退出创建
      if (!answer.isOverwrite) {
        return;
      }
      // 删除文件夹
      fs.removeSync(targetPath);
    }
  }

  const prompts = [];

  if (!pn) {
    const newPn = `spark-${new Date().getTime()}`;
    pn = newPn;
    prompts.push({
      type: 'input',
      name: 'projectName',
      message: 'Enter project name:',
      default: newPn,
    });
  }

  if (!options?.template) {
    prompts.push({
      type: 'list',
      name: 'template',
      message: 'Choose a template:',
      choices: ['vue', 'react', "vue2"],
      default: template,
    });
  }

  prompts.push({
    type: 'input',
    name: 'projectDescription',
    message: 'Enter project description:',
    default: 'A new project',
  });

  const answers = await inquirer.prompt(prompts);
  const finalTemplate = answers.template || template;
  const finalProjectName = answers.projectName || pn;
  const pPath = path.resolve(finalProjectName);
  // fs.mkdirSync(pPath);
  // todo 是否支持 typescript 先写死
  const supportTs = true;
  //获取模板路径，比如 waitkey-cli/commands/templates/vue
  const templatePath = path.join(__dirname, '../../templates', finalTemplate);
  try {
    const loadTemplateSpinner = ora(`download Project ${finalProjectName}...`).start(); // 显示加载条
    processFile(templatePath, {
      spinner: loadTemplateSpinner,
      templatePath,
      targetPath: pPath,
      finalProjectName,
      projectDescription: answers.projectDescription,
      supportTs,
    });
    loadTemplateSpinner.succeed(green.bold(`download Project successfully.`)); // 结束加载条并显示成功消息
    // 展示信息
    console.log(green.bold('运行以下命令以启动项目'));
    console.log('');
    console.log(green.bold(`cd ./${finalProjectName}`));
    console.log(green.bold(`yarn`));
    //  在 vue 中是npm run dev
    console.log(green.bold('yarn start'));
    console.log(blue.bold(textSync(pkg.name || `waiteKey-cli`, {})));
    //todo 之后自动添加依赖 执行 npm install
    // const dependsSpinner = ora(blue.bold(`download dependent...`)).start(); // 显示加载条
    // const command = process.platform === 'win32' ? 'yarn.cmd' : 'yarn';
    // await commandSpawn(command, [], { cwd: `./${finalProjectName}` });
    // dependsSpinner.info(blue.bold(`执行 ${command}操作`)); // 结束加载条并显示成功消息
    // await commandSpawn('cd', [], { cwd: `./${finalProjectName}` });
    // dependsSpinner.info(blue.bold(`执行 cd ./${finalProjectName}操作`)); // 结束加载条并显示成功消息
    // await commandSpawn(command, ['start'], { cwd: `./` });
    // open('http://localhost:8080/');
    // dependsSpinner.succeed(green.bold(`Project ${finalProjectName} created successfully.`)); // 结束加载条并显示成功消息
  } catch (error) {
    console.error('An error occurred:', error);
    // 如果发生错误，删除已经创建的项目文件夹
    if (fs.existsSync(pPath)) {
      fs.removeSync(pPath);
      console.log(`Removed project folder: ${pPath}`);
    }
  }
};

module.exports = creteTemplateCommands;
